import { createRouter, createWebHashHistory } from "vue-router"
import { useRouteStore } from "@/store/route"
import { getRouteList } from "@/api/route"
import NProgress from "nprogress"
import "nprogress/nprogress.css"

//全局进度条的配置
NProgress.configure({
  easing: "ease", // 动画方式，和css动画属性一样（默认：ease）
  speed: 500, // 递增进度条的速度，单位ms（默认： 200）
  showSpinner: false, // 是否显示加载ico
  trickle: true, //是否自动递增
  trickleSpeed: 200, // 自动递增间隔
  minimum: 0.08, // 初始化时的最小百分比，0-1（默认：0.08）
  parent: "body", //指定进度条的父容器
})

const modules = import.meta.glob("../views/**/*.vue")

export const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/login",
      name: "login",
      component: () => import("@/views/login/index.vue"),
      meta: { title: "登录" },
    },
    {
      path: "/",
      name: "layout",
      component: () => import("@/layout/index.vue"),
      redirect: "/home",
      children: [
        {
          path: "/:pathMatch(.*)",
          meta: { title: "404" },
          name: "404",
          component: () => import("@/views/error/404.vue"),
        },
      ],
    },
  ],
})

// 递归扁平化路由
const flattenRoutes = (routes) => {
  let result = []
  routes.forEach((item) => {
    if (item.children) {
      result.push(...flattenRoutes(item.children))
    } else {
      result.push(item)
    }
  })
  return result
}

// 添加动态路由
const addRoute = () => {
  const routeStore = useRouteStore()
  if (routeStore.isUpdate) {
    const routeList = flattenRoutes(routeStore.routeList)
    routeList.forEach((item) => {
      if (!router.hasRoute(item.name)) {
        router.addRoute("layout", {
          ...item,
          component: modules[/* @vite-ignore */ `../${item.component}`],
        })
      }
    })
    routeStore.isUpdate = false
  }
}

// 初始化路由
export const initRouter = async () => {
  let routeList = sessionStorage.getItem("routeList")
    ? JSON.parse(sessionStorage.getItem("routeList"))
    : await getRouteList()
  const routeStore = useRouteStore()
  routeStore.updateRouteList(routeList)
  addRoute()
}

// 根据路径查找菜单项
const findMenuByPath = (menuList, targetPath) => {
  for (const menu of menuList) {
    if (menu.path === targetPath) {
      return menu
    }
    if (menu.children) {
      const found = findMenuByPath(menu.children, targetPath)
      if (found) {
        return menu
      }
    }
  }
  return null
}

// 路由守卫，用于处理路由跳转前的逻辑
router.beforeEach(async (to, from, next) => {
  // 添加动态路由
  addRoute()
  // 进度条开始
  NProgress.start()
  // 设置页面标题
  document.title = to.meta.title
  // 判断是否已登录且没有 token，未登录时重定向到登录页
  const token = localStorage.getItem("token")
  if (to.path !== "/login" && !token) {
    return next({ name: "login" })
  }
  // 设置当前激活的路由
  const routeStore = useRouteStore()
  routeStore.activePath = to.path
  if (to.path !== "/login") {
    routeStore.addTag({ path: to.path, title: to.meta.title })
    routeStore.setActiveMenu(findMenuByPath(routeStore.routeList, to.path))
  }
  next()
})

router.afterEach(() => {
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})
